import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from '../models/order.entity';
import { CreateOrderDto, UpdateOrderDto } from '../models/order.model';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
  ) {}

  findAll(): Promise<Order[]> {
    return this.orderRepository.find();
  }

  findOne(id: number): Promise<Order | null> {
    return this.orderRepository.findOneBy({ id });
  }

  create(orderData: Partial<Order>): Promise<Order> {
    const order = this.orderRepository.create(orderData);
    return this.orderRepository.save(order);
  }

  async update(id: number, orderData: Partial<Order>): Promise<Order | null> {
    const order = await this.findOne(id);
    if (!order) {
      return null;
    }
    this.orderRepository.merge(order, orderData);
    return this.orderRepository.save(order);
  }

  async remove(id: number): Promise<Order | null> {
    const order = await this.findOne(id);
    if (!order) {
      return null;
    }
    return this.orderRepository.remove(order);
  }
}
